package com.handler;

import java.io.IOException;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.BankEntity.BasicInfo;
import com.BankEntity.CreditAppOut;
import com.bstek.uflo.env.Context;
import com.bstek.uflo.model.ProcessInstance;
import com.bstek.uflo.process.handler.ActionHandler;
import com.bstek.uflo.service.ProcessService;
import com.bstek.urule.runtime.KnowledgePackage;
import com.bstek.urule.runtime.KnowledgeSession;
import com.bstek.urule.runtime.KnowledgeSessionFactory;
import com.bstek.urule.runtime.service.KnowledgeService;

@Component
public class AutoOneActionHandler implements ActionHandler {

	@Autowired
	private ProcessService processService;

	@Autowired
	private KnowledgeService knowledgeService;

	@Override
	public void handle(ProcessInstance processInstance, Context context) {

		BasicInfo info = (BasicInfo) processService.getProcessVariable("basicInfo", processInstance.getId());
		CreditAppOut out = (CreditAppOut) processService.getProcessVariable("creditAppOut", processInstance.getId());
		Map<String, Object> params = (Map<String, Object>) processService.getProcessVariable("uruleProcessParam",
				processInstance.getId());
		try {
			KnowledgePackage kp = this.loadKnowledgePackage();
			KnowledgeSession ks = KnowledgeSessionFactory.newKnowledgeSession(kp);
			ks.insert(info);
			ks.insert(out);
			ks.startProcess("autoOneFlow", params);
			int ruleNodes = 0;
			if (out.getRegNo().equals("NBCZ_L101") || out.getRegNo().equals("NBCZ_L201")) {
				ruleNodes = 1;
			} else if (out.getRegNo().equals("NBCZ_L999")) {
				ruleNodes = 2;
			}
			processService.saveProcessVariable(processInstance.getId(), "ruleNodes", ruleNodes);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private KnowledgePackage loadKnowledgePackage() throws IOException {
		return knowledgeService.getKnowledge("Bank/testBank");
	}

}
